package com.mbyte.easy.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mbyte.easy.admin.entity.*;
import com.mbyte.easy.admin.mapper.AllotMapper;
import com.mbyte.easy.admin.mapper.DraftMapper;
import com.mbyte.easy.admin.mapper.RelationMapper;
import com.mbyte.easy.admin.service.*;
import com.mbyte.easy.common.constant.DraftIsPass;
import com.mbyte.easy.common.constant.DraftLogConstant;
import com.mbyte.easy.common.constant.StateDic;
import com.mbyte.easy.common.constant.SysRole;
import com.mbyte.easy.security.entity.SysUser;
import com.mbyte.easy.security.entity.SysUserRoles;
import com.mbyte.easy.security.mapper.SysUserMapper;
import com.mbyte.easy.security.mapper.SysUserRolesMapper;
import com.mbyte.easy.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.mbyte.easy.util.Utility.getUUID;

/**
 * <p>
 * 3的这个音视频校对组长  有用户表id为5和6的 视频校对人 服务实现类
 * </p>
 *
 * @author lp
 * @since 2019-12-12
 */
@Slf4j
@Transactional
@Service
public class RelationServiceImpl extends ServiceImpl<RelationMapper, Relation> implements IRelationService {

    @Autowired
    private AllotMapper allotMapper;
    @Autowired
    private DraftMapper draftMapper;
    @Autowired
    private SysUserRolesMapper userRolesMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private RelationMapper relationMapper;
    @Autowired
    private ICheckPartnerService checkPartnerService;
    @Autowired
    private IDraftService draftService;
    @Autowired
    private IAllotService allotService;
    @Autowired
    private IRelationService relationService;
    @Autowired
    private IGroupService groupService;
    @Autowired
    private SysUserRolesMapper sysUserRolesMapper;
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;



    /**
     * @Description 所有负责人列表
     * @Author myr
     * @param pageNo
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public IPage index(Integer pageNo, Integer pageSize, String name) {
        List<Long> DraftCheckLeader = userRolesMapper.selectByRoleId((long) SysRole.Draft_Check_Leader);
        //所有板块负责人id
        List<Long> BlockLeader = userRolesMapper.selectByRoleId((long) SysRole.Block_Leader);
        Page<SysUser> page = new Page<SysUser>(pageNo, pageSize);
        //板块负责人分页
        IPage<SysUser> pageInfo = sysUserMapper.selectByUserIdForPage(page, BlockLeader);
        return pageInfo;
    }

    /**
     * @Description 稿件校对组长列表
     * @Author myr
     * @param pageNo
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public IPage draftCheckLeaderIndex(Integer pageNo, Integer pageSize, String name){
        List<Long> DraftCheckLeader = userRolesMapper.selectByRoleId((long) SysRole.Draft_Check_Leader);
        Page<SysUser> page = new Page<SysUser>(pageNo, pageSize);
        IPage<SysUser> pageInfo = sysUserMapper.selectByUserIdForPage(page, DraftCheckLeader);
        return pageInfo;
    }

    /**
     * @Description 获取可分配写手
     * @Author myr
     * @return
     **/
    @Override
    public List<SysUser> addBefore() {
        //获取已分配的写手集合
        QueryWrapper<Relation> queryWrapper1 = new QueryWrapper<Relation>();
        queryWrapper1.eq("role_id",SysRole.Writer);
        List<Relation> relations = relationMapper.selectList(queryWrapper1);
        List<Long> userIds = relations.stream().map(Relation::getUserId).collect(Collectors.toList());
        userIds.add(-1l);//防止not in 条件为空报错
        //获取没有分配的写手集合
        QueryWrapper<SysUserRoles> queryWrapper = new QueryWrapper<SysUserRoles>();
        queryWrapper.eq("roles_id",SysRole.Writer).notIn("sys_user_id",userIds);
        List<SysUserRoles> sysUserRoles = userRolesMapper.selectList(queryWrapper);
        List<Long> writerIds = sysUserRoles.stream().map(SysUserRoles::getSysUserId).collect(Collectors.toList());
        if(writerIds.isEmpty()){
            return null;
        }
        IPage<SysUser> sysUserIPage = sysUserMapper.selectByUserIdForPage(new Page(), writerIds);
        List<SysUser> writers = sysUserIPage.getRecords();
        return writers;
    }

    /**
     * @Description 获取可分配稿件校对人
     * @Author myr
     * @return
     **/
    @Override
    public List<SysUser> addCheckerBefore() {
        //获取已分配的稿件校对人集合
        QueryWrapper<Relation> queryWrapper1 = new QueryWrapper<Relation>();
        queryWrapper1.eq("role_id",SysRole.Draft_Checker);
        List<Relation> relations = relationMapper.selectList(queryWrapper1);
        List<Long> checkerIds = relations.stream().map(Relation::getUserId).collect(Collectors.toList());
        checkerIds.add(-1l);//防止not in 条件为空报错
        //获取没有分配的稿件校对人集合
        QueryWrapper<SysUserRoles> queryWrapper = new QueryWrapper<SysUserRoles>();
        queryWrapper.eq("roles_id",SysRole.Draft_Checker).notIn("sys_user_id",checkerIds);
        List<SysUserRoles> sysUserRoles = userRolesMapper.selectList(queryWrapper);
        List<Long> checkerList = sysUserRoles.stream().map(SysUserRoles::getSysUserId).collect(Collectors.toList());
        if(checkerList.isEmpty()){
            return null;
        }
        IPage<SysUser> sysUserIPage = sysUserMapper.selectByUserIdForPage(new Page(), checkerList);
        List<SysUser> checkers = sysUserIPage.getRecords();
        return checkers;
    }

    /**
     * @Description 为版块负责人分配写手
     * @Author myr
     * @param users
     * @param relation
     * @return
     */
    @Override
    public boolean add(String[] users, Relation relation) {
        List<Relation> relations = new ArrayList<>();
        for (int i = 0; i < users.length; i++) {
            Relation rela = new Relation();
            rela.setRoleId(relation.getRoleId());
            rela.setParentId(relation.getParentId());
            rela.setUserId(Long.valueOf(users[i]));
            rela.setCreateTime(LocalDateTime.now());
            rela.setUpdateTime(LocalDateTime.now());
            relations.add(rela);
        }
        return relationService.saveBatch(relations);
    }

    /**
     * @Description 为稿件校对组长分配校对人
     * @Author myr
     * @param users
     * @param relation
     * @return
     */
    @Override
    public boolean addChecker(String[] users, Relation relation) {
        List<Relation> relations = new ArrayList<>();
        for (int i = 0; i < users.length; i++) {
            Relation rela = new Relation();
            rela.setRoleId(relation.getRoleId());
            rela.setParentId(relation.getParentId());
            rela.setUserId(Long.valueOf(users[i]));
            rela.setCreateTime(LocalDateTime.now());
            rela.setUpdateTime(LocalDateTime.now());
            relations.add(rela);
        }
        return relationService.saveBatch(relations);
    }

    /**
     * @Description 稿件校对组长分配稿件给校对人 ，获取所有自己组的校对人
     * @Author myr
     * @return
     **/
    @Override
    public List<SysUser> allotBefore() {
        QueryWrapper<Relation> qw = new QueryWrapper<>();
        log.info("----------------------"+checkPartnerService.getCurrentUser().getId());
        Long loginUser = checkPartnerService.getCurrentUser().getId();
        Long rolesId = sysUserRolesMapper.selectByUserId(loginUser).get(0).getRolesId();
        if(rolesId == SysRole.SEVEN_LEADER) {
            qw.eq("role_id", SysRole.SEVEN_PROOFREADER).eq("parent_id", checkPartnerService.getCurrentUser().getId());
        }else{
            qw.eq("role_id", SysRole.Draft_Checker).eq("parent_id", checkPartnerService.getCurrentUser().getId());
        }
        List<Relation> relationList = relationMapper.selectList(qw);
        List<Long> checkerIdList = relationList.stream().map(Relation::getUserId).collect(Collectors.toList());
        checkerIdList.add(-1L);
        log.info("relationList======"+relationList);
        List<SysUser> checkerList = sysUserMapper.selectByUserIdForPage(new Page(), checkerIdList).getRecords();
        return checkerList;
    }
    /**
     *@author 孙祺至
     *@date 2019/12/20 15:37
     */
    @Override
    public List<SysUser> PPTAllotBefore() {
        QueryWrapper<Relation> qw = new QueryWrapper<>();
        qw.eq("parent_id",checkPartnerService.getCurrentUser().getId());
        List<Relation> relationList = relationMapper.selectList(qw);
        List<Long> checkerIdList = relationList.stream().map(Relation::getUserId).collect(Collectors.toList());
        List<SysUser> checkerList = sysUserMapper.selectByUserIdForPage(new Page(), checkerIdList).getRecords();
        return checkerList;
    }

    /**
     * @Description 稿件校对组长把稿件分配给校对人
     * @Author myr
     * @param checker
     * @param draftId
     * @return
     **/
    @Override
    public boolean allot(String checker, String draftId) {
        Draft draft = new Draft();
        draft.setId(Long.parseLong(draftId));
        draft.setStatusCode(StateDic.Draft_Allocated);
        draft.setIsPass(DraftIsPass.Pass);
        draft.setUpdateTime(LocalDateTime.now());
        draft.setLastOperator(checkPartnerService.getCurrentUser().getId());
        draft.setGroupId(checker);
        log.info("draftCheckLeader update --> {}",draft);//更新稿件状态
        boolean updateDraft = retBool(Integer.valueOf(draftMapper.updateById(draft)));
        Allot allot = new Allot();
        allot.setDraftId(Long.valueOf(draftId));
        allot.setAllotnoId(Long.valueOf(checker));
        allot.setAllotId(checkPartnerService.getCurrentUser().getId());
        allot.setStatusCode(StateDic.Draft_Allocated);
        allot.setUpdateTime(LocalDateTime.now());
        allot.setCreateTime(LocalDateTime.now());
        log.info("draftCheckLeader update --> {}",allot);//更新分配表
        return this.retBool(Integer.valueOf(allotMapper.insert(allot))) && updateDraft;
    }

    /**
     * @Description 稿件校对组长批量把稿件分配给校对人
     * @Author myr
     * @param checker
     * @param draftId
     * @return
     **/
    @Override
    public boolean allotDrafts(String checker, String draftId,String name) {
        Long loginUser = checkPartnerService.getCurrentUser().getId();
        Long rolesId = sysUserRolesMapper.selectByUserId(loginUser).get(0).getRolesId();

        int[] draftIds = StringUtil.stringConvertInt(draftId);
        String groupid = getUUID();
        List<Draft> draftList = new ArrayList<>();
        if(rolesId == SysRole.SEVEN_LEADER){
            log.info("我是七队");
            for (int i = 0; i < draftIds.length; i++) {
                Draft draft = new Draft();
                draft.setId(draftIds[i]);
                draft.setStatusCode(StateDic.DRAFT_ALLOCATED_SEVEN);
                draft.setIsPass(DraftIsPass.Pass);
                draft.setUpdateTime(LocalDateTime.now());
                draft.setLastOperator(checkPartnerService.getCurrentUser().getId());
                draft.setGroupId(groupid);
                draftList.add(draft);
                //插入操作日志 分配
                applicationEventPublisher.publishEvent(new DraftLog().setActionType(DraftLogConstant.ACTION_ALLOT)
                        .setDraftId((long) draftIds[i]).setGroupId(groupid));
            }
        }else {
            for (int i = 0; i < draftIds.length; i++) {
                Draft draft = new Draft();
                draft.setId(draftIds[i]);
                draft.setStatusCode(StateDic.Draft_Allocated);
                draft.setIsPass(DraftIsPass.Pass);
                draft.setUpdateTime(LocalDateTime.now());
                draft.setLastOperator(checkPartnerService.getCurrentUser().getId());
                draft.setGroupId(groupid);
                draftList.add(draft);
                //插入操作日志 分配
                applicationEventPublisher.publishEvent(new DraftLog().setActionType(DraftLogConstant.ACTION_ALLOT)
                        .setDraftId((long) draftIds[i]).setGroupId(groupid));
            }
        }
        log.info("draftCheckLeader update --> {}",draftList);//更新稿件状态
        boolean updateDraft = draftService.updateBatchById(draftList);
        List<Allot> allotList = new ArrayList<>();
        if(rolesId == SysRole.SEVEN_LEADER){
            for (int i = 0; i < draftIds.length; i++) {
                Allot allot = new Allot();
                allot.setDraftId(Long.valueOf(draftIds[i]));
                allot.setAllotnoId(Long.valueOf(checker));
                allot.setAllotId(checkPartnerService.getCurrentUser().getId());
                allot.setStatusCode(StateDic.DRAFT_ALLOCATED_SEVEN);
                allot.setUpdateTime(LocalDateTime.now());
                allot.setCreateTime(LocalDateTime.now());
                allotList.add(allot);
            }
        }else {
            for (int i = 0; i < draftIds.length; i++) {
                Allot allot = new Allot();
                allot.setDraftId(Long.valueOf(draftIds[i]));
                allot.setAllotnoId(Long.valueOf(checker));
                allot.setAllotId(checkPartnerService.getCurrentUser().getId());
                allot.setStatusCode(StateDic.Draft_Allocated);
                allot.setUpdateTime(LocalDateTime.now());
                allot.setCreateTime(LocalDateTime.now());
                allotList.add(allot);
            }
        }
        Group group = new Group();
        group.setName(name);
        group.setUserId(Long.valueOf(checker));
        group.setGroupId(groupid);
        groupService.save(group);
        log.info("draftCheckLeader update --> {}",allotList);//更新分配表
        boolean saveAllot = allotService.saveBatch(allotList);
        return saveAllot && updateDraft;
    }
}
